<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">




<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
  </script>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />



  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico?v=5.1.4">







  <meta name="keywords" content="Swift," />





  <link rel="alternate" href="/atom.xml" title="Swift社区" type="application/atom+xml" />






<meta name="description" content="前言不久前，我正在工作中开发一项新服务，该服务由 Swift Package 组成，该 Package 公开了一个类似于Decodable协议，供我们应用程序的其余部分使用。事实上，该协议是从Decodable本身继承下来的，看起来像这样：   Fetchable.swit  1protocol Fetchable: Decodable, Equatable &amp;#123;&amp;#125;">
<meta name="keywords" content="Swift">
<meta property="og:type" content="article">
<meta property="og:title" content="使用 Swift Package 插件生成代码">
<meta property="og:url" content="https://fanbaoying.github.io/使用-Swift-Package-插件生成代码/index.html">
<meta property="og:site_name" content="Swift社区">
<meta property="og:description" content="前言不久前，我正在工作中开发一项新服务，该服务由 Swift Package 组成，该 Package 公开了一个类似于Decodable协议，供我们应用程序的其余部分使用。事实上，该协议是从Decodable本身继承下来的，看起来像这样：   Fetchable.swit  1protocol Fetchable: Decodable, Equatable &amp;#123;&amp;#125;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://www.polpiella.dev/assets/posts/code-generation-using-swift-package-plugins/release-notes.png">
<meta property="og:updated_time" content="2022-08-25T04:10:42.979Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用 Swift Package 插件生成代码">
<meta name="twitter:description" content="前言不久前，我正在工作中开发一项新服务，该服务由 Swift Package 组成，该 Package 公开了一个类似于Decodable协议，供我们应用程序的其余部分使用。事实上，该协议是从Decodable本身继承下来的，看起来像这样：   Fetchable.swit  1protocol Fetchable: Decodable, Equatable &amp;#123;&amp;#125;">
<meta name="twitter:image" content="https://www.polpiella.dev/assets/posts/code-generation-using-swift-package-plugins/release-notes.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://fanbaoying.github.io/使用-Swift-Package-插件生成代码/"/>





  <title>使用 Swift Package 插件生成代码 | Swift社区</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/SwiftCommunityRes" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Swift社区</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">做最好的 Swift 社区</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://fanbaoying.github.io/使用-Swift-Package-插件生成代码/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Swift社区">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/84354365?v=4">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Swift社区">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用 Swift Package 插件生成代码</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-08-25T11:42:38+08:00">
                2022-08-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift-文集/" itemprop="url" rel="index">
                    <span itemprop="name">Swift 文集</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                -->
                <span title="字数统计">
                  数字统计 3,390字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                --> 

                <span title="阅读时长">
                  阅读时长 14分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>不久前，我正在工作中开发一项新服务，该服务由 Swift Package 组成，该 Package 公开了一个类似于<code>Decodable</code>协议，供我们应用程序的其余部分使用。事实上，该协议是从<code>Decodable</code>本身继承下来的，看起来像这样：</p>
<blockquote>
<p> Fetchable.swit</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Fetchable</span>: <span class="title">Decodable</span>, <span class="title">Equatable</span> </span>&#123;&#125;</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>新的 package 将采用符合<code>Fetchable</code>的类型来尝试从远程或缓存的JSON数据块中解码它们。</p>
<p>由于这项服务对应用程序的正确运行至关重要，作为这项工作的一部分，我们希望确保始终存在故障安全（ fail-safe）。因此，我们让该应用程序附带了一个备用的JSON文件，如果远程和缓存的数据解码失败，将使用该文件，来保证程序的正常运行。</p>
<p><strong>无论如何</strong>，我们需要符合<code>Fetchable</code>的新类型从备用数据中正确解码。然而，有一个问题，有时很难发现备用JSON文件或模型本身是否有任何错误，因为解码错误会在<strong>运行时</strong>发生，并且只有在访问某些屏幕/功能时才会发生。</p>
<p>为了让我们对我们要发送的代码更有<strong>信心</strong>，我们添加了一些<strong>单元测试</strong>，试图根据我们附带的备用JSON解码符合<code>Fetchable</code>协议的每个模型。这些将使我们在CI上有一个早期指示，表明备用数据或模型中存在错误，如果所有测试都通过，我们将确定，一旦我们发布新服务，它始终具有<strong>故障安全功能</strong>。</p>
<p>我们<strong>手动</strong>编写了这些测试，但我们很快就意识到这个解决方案是<strong>不可扩展的</strong>，因为随着越来越多的符合<code>Fetchable</code>协议的类型被添加，我们引入了大量的代码复制，并可能有人最终忘记为特定功能编写这些测试。</p>
<p>我们考虑过自动化该过程，但由于我们的代码库的性质，我们遇到了一些问题，代码库高度模块化，混合了Xcode项目和Swift Package。一些架构决策还意味着我们必须收集大量符号信息，才能获得生成测试的正确类型。</p>
<h2 id="是什么让我再次关注到它？"><a href="#是什么让我再次关注到它？" class="headerlink" title="是什么让我再次关注到它？"></a>是什么让我再次关注到它？</h2><p>在我忘记了这件事一段时间后，Xcode 14的公告允许在Xcode项目中使用 Swift Package 插件，以及一些架构更改使提取类型信息变得容易得多，这让我有动力再次开始研究这个问题。</p>
<blockquote>
<p>请注意，Xcode项目的构建工具插件尚未按照发布说明在Xcode 14 Beta 2中提供，但将在Xcode 14的未来版本中提供。</p>
<p><img src="https://www.polpiella.dev/assets/posts/code-generation-using-swift-package-plugins/release-notes.png" alt="图片取自 Xcode Beta 2 版的发布说明"></p>
</blockquote>
<p>在过去的几周里，我一直在研究如何使用软件包插件生成单元测试，在这篇文章中，我将解释我在向哪个方向尝试以及它涉及了什么。</p>
<h2 id="实施细节"><a href="#实施细节" class="headerlink" title="实施细节"></a>实施细节</h2><p>我开始了一项任务，即创建一个<a href="https://www.polpiella.dev/an-early-look-at-swift-extensible-build-tools" target="_blank" rel="noopener">构建工具插件</a>，与 Xcode 14 引入的<a href="https://github.com/apple/swift-evolution/blob/main/proposals/0332-swiftpm-command-plugins.md" target="_blank" rel="noopener">命令插件</a>不同，该插件可以任意运行并依赖用户输入，作为Swift软件包构建过程的一部分运行。</p>
<p>我知道我需要创建一个可执行文件，因为 Build Tool 插件依赖这些来执行操作。这个脚本将完全用 Swift 编写，因为这是我最熟悉的语言，并承担以下职责：</p>
<ol>
<li>扫描目标目录并提取所有<code>.swift</code>文件。目标将被递归扫描，以确保不会错过子目录。</li>
<li>使用<a href="https://github.com/apple/swift/tree/main/tools/SourceKit" target="_blank" rel="noopener">sourcekit</a>，或者更具体地说，<a href="https://github.com/jpsim/SourceKitten" target="_blank" rel="noopener">SourceKitten</a>，扫描这些<code>.swift</code>文件并收集类型信息。这将允许提取符合<code>Fetchable</code>协议的所有类型，以便可以针对它们编写测试。</li>
<li>获得这些类型后，生成一个带有<code>XCTestCase</code>的<code>.swift</code>文件，其中包含每种类型的单元测试。</li>
</ol>
<h2 id="让我们写一些代码吧"><a href="#让我们写一些代码吧" class="headerlink" title="让我们写一些代码吧"></a>让我们写一些代码吧</h2><p>与所有 Swift Package 一样，最简单的入门方法是在命令行上运行<code>swift package init</code>。</p>
<p>这创建了两个目标，一个是包含<code>Fetchable</code>协议定义和符合该定义的类型的实现代码，另一个是应用插件为此类类型生成单元测试的测试目标。</p>
<blockquote>
<p>Package.swit</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// swift-tools-version: 5.6</span></span><br><span class="line"><span class="comment">// The swift-tools-version declares the minimum version of Swift required to build this package.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> PackageDescription</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> package = <span class="type">Package</span>(</span><br><span class="line">    name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">    platforms: [.macOS(.v10_11)],</span><br><span class="line">    products: [</span><br><span class="line">        .library(</span><br><span class="line">            name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">            targets: [<span class="string">"CodeGenSample"</span>]),</span><br><span class="line">    ],</span><br><span class="line">    dependencies: [</span><br><span class="line">    ],</span><br><span class="line">    targets: [</span><br><span class="line">        .target(</span><br><span class="line">            name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">            dependencies: []</span><br><span class="line">        ),</span><br><span class="line">        .testTarget(</span><br><span class="line">            name: <span class="string">"CodeGenSampleTests"</span>,</span><br><span class="line">            dependencies: [<span class="string">"CodeGenSample"</span>]</span><br><span class="line">        )</span><br><span class="line">     ]</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<h3 id="编写可执行文件"><a href="#编写可执行文件" class="headerlink" title="编写可执行文件"></a>编写可执行文件</h3><p>如前所述，所有构建工具插件都需要可执行文件来执行所有必要的操作。</p>
<p>为了帮助开发此命令行，将使用几个依赖项。第一个是<a href="https://github.com/jpsim/SourceKitten" target="_blank" rel="noopener">SourceKitten</a>——特别是其SourceKitten框架库，这是一个Swift包装器，用于帮助使用Swift代码编写<a href="https://github.com/apple/swift/tree/main/tools/SourceKit" target="_blank" rel="noopener">sourcekit</a>请求，第二个是<a href="https://github.com/apple/swift-argument-parser" target="_blank" rel="noopener">快速参数解析器</a>，这是苹果提供的软件包，可以轻松创建命令行工具，并以更快、更安全的方式解析在执行过程中传递的命令行参数。</p>
<p>在创建<code>executableTarget</code>并赋予它两个依赖项后，<code>Package.swift</code>就是这个样子：</p>
<blockquote>
<p>Package.swift</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// swift-tools-version: 5.6</span></span><br><span class="line"><span class="comment">// The swift-tools-version declares the minimum version of Swift required to build this package.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> PackageDescription</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> package = <span class="type">Package</span>(</span><br><span class="line">    name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">    platforms: [.macOS(.v10_11)],</span><br><span class="line">    products: [</span><br><span class="line">        .library(</span><br><span class="line">            name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">            targets: [<span class="string">"CodeGenSample"</span>]),</span><br><span class="line">    ],</span><br><span class="line">    dependencies: [</span><br><span class="line">        .package(url: <span class="string">"https://github.com/jpsim/SourceKitten.git"</span>, exact: <span class="string">"0.32.0"</span>),</span><br><span class="line">        .package(url: <span class="string">"https://github.com/apple/swift-argument-parser"</span>, from: <span class="string">"1.0.0"</span>)</span><br><span class="line">    ],</span><br><span class="line">    targets: [</span><br><span class="line">        .target(</span><br><span class="line">            name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">            dependencies: []</span><br><span class="line">        ),</span><br><span class="line">        .testTarget(</span><br><span class="line">            name: <span class="string">"CodeGenSampleTests"</span>,</span><br><span class="line">            dependencies: [<span class="string">"CodeGenSample"</span>]</span><br><span class="line">        ),</span><br><span class="line">        .executableTarget(</span><br><span class="line">            name: <span class="string">"PluginExecutable"</span>,</span><br><span class="line">            dependencies: [</span><br><span class="line">                .product(name: <span class="string">"SourceKittenFramework"</span>, package: <span class="string">"SourceKitten"</span>),</span><br><span class="line">                .product(name: <span class="string">"ArgumentParser"</span>, package: <span class="string">"swift-argument-parser"</span>)</span><br><span class="line">            ]</span><br><span class="line">        )</span><br><span class="line">     ]</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>可执行目标需要一个入口点，因此，在<code>PluginExecutable</code>目标的源目录下，必须创建一个名为<code>PluginExecutable.swift</code>的文件，其中所有可执行逻辑都需要创建。</p>
<blockquote>
<p>请注意，这个文件可以随心所欲地命名，我倾向于以与我在<code>Package.swift</code>中创建的目标相同的方式命名它。</p>
</blockquote>
<p>如下所示的脚本导入必要的依赖项，并创建可执行文件的入口点（必须用<code>@main</code>装饰），并声明在执行时传递的4个输入。</p>
<p>所有逻辑和方法调用都存在于<code>run</code>函数中，该函数是调用可执行文件时运行的方法。这是<code>ArgumentParser</code>语法的一部分，如果您想了解更多信息，<a href="https://www.andyibanez.com/posts/writing-commandline-tools-argumentparser-part1/" target="_blank" rel="noopener">Andy Ibañez</a>有<a href="https://www.andyibanez.com/posts/writing-commandline-tools-argumentparser-part1/" target="_blank" rel="noopener">一篇</a>关于该主题<a href="https://www.andyibanez.com/posts/writing-commandline-tools-argumentparser-part1/" target="_blank" rel="noopener">的精彩文章</a>，可能非常有帮助。</p>
<blockquote>
<p>PluginExecutable.swift</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> SourceKittenFramework</span><br><span class="line"><span class="keyword">import</span> ArgumentParser</span><br><span class="line"><span class="keyword">import</span> Foundation</span><br><span class="line"></span><br><span class="line">@main</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">PluginExecutable</span>: <span class="title">ParsableCommand</span> </span>&#123;</span><br><span class="line">    @<span class="type">Argument</span>(help: <span class="string">"The protocol name to match"</span>)</span><br><span class="line">    <span class="keyword">var</span> protocolName: <span class="type">String</span></span><br><span class="line"></span><br><span class="line">    @<span class="type">Argument</span>(help: <span class="string">"The module's name"</span>)</span><br><span class="line">    <span class="keyword">var</span> moduleName: <span class="type">String</span></span><br><span class="line"></span><br><span class="line">    @<span class="type">Option</span>(help: <span class="string">"Directory containing the swift files"</span>)</span><br><span class="line">    <span class="keyword">var</span> input: <span class="type">String</span></span><br><span class="line"></span><br><span class="line">    @<span class="type">Option</span>(help: <span class="string">"The path where the generated files will be created"</span>)</span><br><span class="line">    <span class="keyword">var</span> output: <span class="type">String</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">run</span><span class="params">()</span></span> <span class="keyword">throws</span> &#123;</span><br><span class="line">		<span class="comment">// 1</span></span><br><span class="line">        <span class="keyword">let</span> files = <span class="keyword">try</span> deepSearch(<span class="type">URL</span>(fileURLWithPath: input, isDirectory: <span class="literal">true</span>))</span><br><span class="line">        <span class="comment">// 2</span></span><br><span class="line">        setenv(<span class="string">"IN_PROCESS_SOURCEKIT"</span>, <span class="string">"YES"</span>, <span class="number">1</span>)</span><br><span class="line">        <span class="keyword">let</span> structures = <span class="keyword">try</span> files.<span class="built_in">map</span> &#123; <span class="keyword">try</span> <span class="type">Structure</span>(file: <span class="type">File</span>(path: $<span class="number">0</span>.path)!) &#125;</span><br><span class="line">        <span class="comment">// 3</span></span><br><span class="line">        <span class="keyword">var</span> matchedTypes = [<span class="type">String</span>]()</span><br><span class="line">        structures.forEach &#123; walkTree(dictionary: $<span class="number">0</span>.dictionary, acc: &amp;matchedTypes) &#125;</span><br><span class="line">        <span class="comment">// 4</span></span><br><span class="line">        <span class="keyword">try</span> createOutputFile(withContent: matchedTypes)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>现在让我们专注于上面的<code>run</code>方法，以了解当插件运行可执行文件时会发生什么：</p>
<ol>
<li>首先，扫描目标目录以找到其中的所有<code>.swift</code>文件。这是递归完成的，这样子目录就不会错过。此目录的路径作为参数传递给可执行文件。</li>
<li>对于上次调用中找到的每个文件，通过<a href="https://github.com/jpsim/SourceKitten" target="_blank" rel="noopener">SourceKitten</a>发出<code>Structure</code>请求，以查找文件中Swift代码的类型信息。请注意，环境变量（<code>IN_PROCESS_SOURCEKIT</code>）也被设置为true。这需要确保选择源套件的进程中版本，以便它能够遵守插件的沙盒规则。</li>
</ol>
<blockquote>
<p>Xcode附带两个版本的sourcekit可执行文件，一个版本解析进程中的文件，另一个使用XPC向解析进程外文件的守护进程发送请求。后者是mac上的默认版本，为了能够将sourcekit用作插件进程的一部分，必须选择进程中版本。<a href="https://github.com/jpsim/SourceKitten/pull/728" target="_blank" rel="noopener">这最近在SourceKitten上作为环境变量实现</a>，是运行引擎盖下使用sourcekit的其他可执行文件的关键，例如<code>SwiftLint</code>。</p>
</blockquote>
<ol>
<li><p>浏览上次调用的所有响应，并扫描类型信息以提取符合<code>Fetchable</code>协议的任何类型。</p>
</li>
<li><p>在传递给可执行文件的<code>output</code>参数指定的位置创建一个输出文件，其中包含每种类型的单元测试。</p>
</li>
</ol>
<blockquote>
<p>请注意，上面没有重点介绍每个调用的具体细节，但如果你对实现感兴趣，包含所有代码的repo现在已经在Github上公开了! </p>
</blockquote>
<h3 id="创建该插件"><a href="#创建该插件" class="headerlink" title="创建该插件"></a>创建该插件</h3><p>与可执行文件一样，必须向<code>Package.swift</code>添加<code>.plugin</code>目标，并且必须创建包含插件实现的<code>.swift</code>文件（<code>Plugins/SourceKitPlugin/SourceKitPlugin.swift</code>）。</p>
<blockquote>
<p>Package.swift</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// swift-tools-version: 5.6</span></span><br><span class="line"><span class="comment">// The swift-tools-version declares the minimum version of Swift required to build this package.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> PackageDescription</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> package = <span class="type">Package</span>(</span><br><span class="line">    name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">    platforms: [.macOS(.v10_11)],</span><br><span class="line">    products: [</span><br><span class="line">        .library(</span><br><span class="line">            name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">            targets: [<span class="string">"CodeGenSample"</span>]),</span><br><span class="line">    ],</span><br><span class="line">    dependencies: [</span><br><span class="line">        .package(url: <span class="string">"https://github.com/jpsim/SourceKitten.git"</span>, exact: <span class="string">"0.32.0"</span>),</span><br><span class="line">        .package(url: <span class="string">"https://github.com/apple/swift-argument-parser"</span>, from: <span class="string">"1.0.0"</span>)</span><br><span class="line">    ],</span><br><span class="line">    targets: [</span><br><span class="line">        .target(</span><br><span class="line">            name: <span class="string">"CodeGenSample"</span>,</span><br><span class="line">            dependencies: []</span><br><span class="line">        ),</span><br><span class="line">        .testTarget(</span><br><span class="line">            name: <span class="string">"CodeGenSampleTests"</span>,</span><br><span class="line">            dependencies: [“<span class="type">CodeGenSample</span><span class="string">"],</span></span><br><span class="line"><span class="string">plugins: [“SourceKitPlugin”],</span></span><br><span class="line"><span class="string">        ),</span></span><br><span class="line"><span class="string">        .executableTarget(</span></span><br><span class="line"><span class="string">            name: "</span><span class="type">PluginExecutable</span><span class="string">",</span></span><br><span class="line"><span class="string">            dependencies: [</span></span><br><span class="line"><span class="string">                .product(name: "</span><span class="type">SourceKittenFramework</span><span class="string">", package: "</span><span class="type">SourceKitten</span><span class="string">"),</span></span><br><span class="line"><span class="string">                .product(name: "</span><span class="type">ArgumentParser</span><span class="string">", package: "</span>swift-argument-parser<span class="string">")</span></span><br><span class="line"><span class="string">            ]</span></span><br><span class="line"><span class="string">        ),</span></span><br><span class="line"><span class="string">        .plugin(</span></span><br><span class="line"><span class="string">            name: "</span><span class="type">SourceKitPlugin</span><span class="string">",</span></span><br><span class="line"><span class="string">            capability: .buildTool(),</span></span><br><span class="line"><span class="string">            dependencies: [.target(name: "</span><span class="type">PluginExecutable</span><span class="string">")]</span></span><br><span class="line"><span class="string">        )</span></span><br><span class="line"><span class="string">     ]</span></span><br><span class="line"><span class="string">)</span></span><br></pre></td></tr></table></figure>
<p>以下代码显示了插件的初始实现，其<code>struct</code>符合<code>BuildToolPlugin</code>的协议。这需要实现一个返回具有单个构建命令的数组的<code>createBuildCommands</code>方法。</p>
<blockquote>
<p>此插件使用<code>buildCommand</code>而不是<code>preBuildCommand</code>，因为它需要作为构建过程的一部分运行，而不是在它之前运行，因此它有机会构建和使用它所依赖的可执行文件。在这种情况下，支持使用<code>buildCommand</code>的另一点是，它只会在输入文件更改时运行，而不是每次构建目标时运行。</p>
</blockquote>
<p>此命令必须为要运行的可执行文件提供名称和路径，这可以在插件的上下文中找到：</p>
<blockquote>
<p>SourceKitPlugin.swift</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PackagePlugin</span><br><span class="line"></span><br><span class="line">@main</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">SourceKitPlugin</span>: <span class="title">BuildToolPlugin</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">createBuildCommands</span><span class="params">(context: PluginContext, target: Target)</span></span> async <span class="keyword">throws</span> -&gt; [<span class="type">Command</span>] &#123;</span><br><span class="line">        <span class="keyword">return</span> [</span><br><span class="line">            .buildCommand(</span><br><span class="line">                displayName: <span class="string">"Protocol Extraction!"</span>,</span><br><span class="line">                executable: <span class="keyword">try</span> context.tool(named: <span class="string">"PluginExecutable"</span>).path,</span><br><span class="line">                arguments: [</span><br><span class="line">                    <span class="string">"FindThis"</span>,</span><br><span class="line">                    🤷,</span><br><span class="line">                    <span class="string">"--input"</span>,</span><br><span class="line">                    🤷,</span><br><span class="line">                    <span class="string">"--output"</span>,</span><br><span class="line">                    🤷</span><br><span class="line">                ],</span><br><span class="line">                environment: [<span class="string">"IN_PROCESS_SOURCEKIT"</span>: <span class="string">"YES"</span>],</span><br><span class="line">                outputFiles: [🤷]</span><br><span class="line">            )</span><br><span class="line">        ]</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如上面的代码所示，还有一些空白需要填充（🤷）：</p>
<ol>
<li><p>提供<code>outputPath</code>，用于生成单元测试文件。此文件可以在<code>pluginWorkDirectory</code>中生成，也可以在插件的上下文中找到。该目录提供读写权限且其中创建的任何文件都将是软件包构建过程的一部分。</p>
</li>
<li><p>提供输入路径和模块名称。这是最棘手的部分，这些需要指向正在测试的目标的来源，而不是插件正在应用于的目标——单元测试。谢天谢地，插件的目标依赖项是可访问的，我们可以从该数组中获取我们感兴趣的依赖项。此依赖项将是内部的（<code>target</code>而不是<code>product</code>），它将为可执行文件提供其名称和目录。</p>
</li>
</ol>
<blockquote>
<p>SourceKitPlugin.swift</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PackagePlugin</span><br><span class="line"></span><br><span class="line">@main</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">SourceKitPlugin</span>: <span class="title">BuildToolPlugin</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">createBuildCommands</span><span class="params">(context: PluginContext, target: Target)</span></span> async <span class="keyword">throws</span> -&gt; [<span class="type">Command</span>] &#123;</span><br><span class="line">        <span class="keyword">let</span> outputPath = context.pluginWorkDirectory.appending(“<span class="type">GeneratedTests</span>.swift”)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">guard</span> <span class="keyword">let</span> dependencyTarget = target</span><br><span class="line">            .dependencies</span><br><span class="line">            .compactMap &#123; dependency -&gt; <span class="type">Target</span>? <span class="keyword">in</span></span><br><span class="line">                <span class="keyword">switch</span> dependency &#123;</span><br><span class="line">                <span class="keyword">case</span> .target(<span class="keyword">let</span> target): <span class="keyword">return</span> target</span><br><span class="line">                <span class="keyword">default</span>: <span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            .<span class="built_in">filter</span> &#123; <span class="string">"<span class="subst">\($<span class="number">0</span>.name)</span>Tests"</span> == target.name  &#125;</span><br><span class="line">            .first <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="type">Diagnostics</span>.error(<span class="string">"Could not get a dependency to scan!”)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">                return []</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">        return [</span></span><br><span class="line"><span class="string">            .buildCommand(</span></span><br><span class="line"><span class="string">                displayName: "</span><span class="type">Protocol</span> <span class="type">Extraction</span>!<span class="string">",</span></span><br><span class="line"><span class="string">                executable: try context.tool(named: "</span><span class="type">PluginExecutable</span><span class="string">").path,</span></span><br><span class="line"><span class="string">                arguments: [</span></span><br><span class="line"><span class="string">                    "</span><span class="type">Fetchable</span><span class="string">",</span></span><br><span class="line"><span class="string">	                 dependencyTarget.name,</span></span><br><span class="line"><span class="string">                    "</span>--input<span class="string">",</span></span><br><span class="line"><span class="string">                    dependencyTarget.directory,</span></span><br><span class="line"><span class="string">                    "</span>--output<span class="string">",</span></span><br><span class="line"><span class="string">                    outputPath</span></span><br><span class="line"><span class="string">                ],</span></span><br><span class="line"><span class="string">                environment: ["</span><span class="type">IN_PROCESS_SOURCEKIT</span><span class="string">": "</span><span class="type">YES</span><span class="string">"],</span></span><br><span class="line"><span class="string">                outputFiles: [outputPath]</span></span><br><span class="line"><span class="string">            )</span></span><br><span class="line"><span class="string">        ]</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意上述可选性处理方式。如果在测试目标的依赖项中找不到<em>合适的</em>目标，则使用<a href="https://github.com/apple/swift-evolution/blob/main/proposals/0303-swiftpm-extensible-build-tools.md#plugin-api" target="_blank" rel="noopener">Diagnostics API</a>将错误转发回Xcode，并告诉它完成构建过程。</p>
</blockquote>
<h2 id="让我们看下结果"><a href="#让我们看下结果" class="headerlink" title="让我们看下结果"></a>让我们看下结果</h2><p>插件这就完成了！现在让我们在 Xcode 中运行它！为了测试这种方法，将包含以下内容的文件添加到<code>CodeGenSample</code>目标中：</p>
<blockquote>
<p>CodeGenSample.swift</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Foundation</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Fetchable</span>: <span class="title">Decodable</span>, <span class="title">Equatable</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">FeatureABlock</span>: <span class="title">Fetchable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> featureA: <span class="type">FeatureA</span></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">FeatureA</span>: <span class="title">Fetchable</span> </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> url: <span class="type">URL</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">enum</span> <span class="title">Root</span> </span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">RootBlock</span>: <span class="title">Fetchable</span> </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> url: <span class="type">URL</span></span><br><span class="line">        <span class="keyword">let</span> areAllFeaturesEnabled: <span class="type">Bool</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>请注意，脚本将在结构中首次出现<code>Fetchable</code>协议时停止。这意味着任何嵌套的符合<code>Fetchable</code>协议的类型都将被测试，只是外部模型。</p>
</blockquote>
<p>给定此输入并在主目标上运行测试，生成并运行<code>XCTestCase</code>，其中包含符合<code>Fetchable</code>协议的两种类型的测试。</p>
<blockquote>
<p>GeneratedTests.swift</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> XCTest</span><br><span class="line"><span class="meta">@testable</span> <span class="keyword">import</span> CodeGenSample</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GeneratedTests</span>: <span class="title">XCTestCase</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">func</span> <span class="title">testFeatureABlock</span><span class="params">()</span></span> &#123;</span><br><span class="line">		assertCanParseFromDefaults(<span class="type">FeatureABlock</span>.<span class="keyword">self</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">func</span> <span class="title">testRoot_RootBlock</span><span class="params">()</span></span> &#123;</span><br><span class="line">		assertCanParseFromDefaults(<span class="type">Root</span>.<span class="type">RootBlock</span>.<span class="keyword">self</span>)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">func</span> <span class="title">assertCanParseFromDefaults</span>&lt;T: Fetchable&gt;<span class="params">(<span class="number">_</span> type: T.<span class="keyword">Type</span>)</span></span> &#123;</span><br><span class="line">        <span class="comment">// Logic goes here...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>所有测试都通过了😅✅而且，尽管他们目前没有做很多事情，但可以扩展实现，以提供一些示例数据和一个<code>JSONDecoder</code>实例来对每个单元测试进行解析。</p>
<h2 id="关于我们"><a href="#关于我们" class="headerlink" title="关于我们"></a>关于我们</h2><p>我们是由 Swift 爱好者共同维护，我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术内容，也整理收集优秀的学习资料。</p>
<p>后续还会翻译大量资料到我们公众号，有感兴趣的朋友，可以加入我们。</p>

      
    </div>
    
    
    
    

    
      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    


    
      <div>
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/使用-Swift-Package-插件生成代码/">使用 Swift Package 插件生成代码</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Swift社区 的个人博客">Swift社区</a></p>
  <p><span>发布时间:</span>2022年08月25日 - 11:08</p>
  <p><span>最后更新:</span>2022年08月25日 - 12:08</p>
  <p><span>原始链接:</span><a href="/使用-Swift-Package-插件生成代码/" title="使用 Swift Package 插件生成代码">https://fanbaoying.github.io/使用-Swift-Package-插件生成代码/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://fanbaoying.github.io/使用-Swift-Package-插件生成代码/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      </div>
    


    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="Swift社区 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Swift社区 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Swift/" rel="tag"><i class="fa fa-tag"></i> Swift</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/使用-Swift-的并发系统并行运行多个任务/" rel="next" title="使用 Swift 的并发系统并行运行多个任务">
                <i class="fa fa-chevron-left"></i> 使用 Swift 的并发系统并行运行多个任务
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/App-Store-已上架项目打开瞬闪问题/" rel="prev" title="App Store 已上架项目打开瞬闪问题">
                App Store 已上架项目打开瞬闪问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://avatars.githubusercontent.com/u/84354365?v=4"
                alt="Swift社区" />
            
              <p class="site-author-name" itemprop="name">Swift社区</p>
              <p class="site-description motion-element" itemprop="description">我们的使命是做一个最专业最权威的 Swift 中文社区，我们的愿景是希望更多的人学习和使用Swift。我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术干货，不忘初心，牢记使命。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">187</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_36478920" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/5a30d987f265da430d580126" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-spinner"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/fanbaoying" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/swift-community" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/7711465033" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzAxNzgzNTgwMw==&action=getalbum&album_id=2024314764775981057" target="_blank" title="公众号">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftWeekly" title="SwiftWeekly" target="_blank">SwiftWeekly</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/article-ios" title="Article-ios" target="_blank">Article-ios</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftUI-Book" title="SwiftUI-Book" target="_blank">SwiftUI-Book</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#是什么让我再次关注到它？"><span class="nav-number">2.</span> <span class="nav-text">是什么让我再次关注到它？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实施细节"><span class="nav-number">3.</span> <span class="nav-text">实施细节</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#让我们写一些代码吧"><span class="nav-number">4.</span> <span class="nav-text">让我们写一些代码吧</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#编写可执行文件"><span class="nav-number">4.1.</span> <span class="nav-text">编写可执行文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建该插件"><span class="nav-number">4.2.</span> <span class="nav-text">创建该插件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#让我们看下结果"><span class="nav-number">5.</span> <span class="nav-text">让我们看下结果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关于我们"><span class="nav-number">6.</span> <span class="nav-text">关于我们</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Swift社区</span>

  
</div>

<!-- 
<div class="powered-by">
  <i class="fa fa-user-md">
  </i>
  <span id="busuanzi_container_site_uv">
    已有<span id="busuanzi_value_site_uv"></span>人来访
  </span>

</div>


  <span class="post-meta-divider">|</span>


<div class="powered-by">
  <i class="fa fa-eye"></i>
  <span id="busuanzi_container_site_pv">
      访问量<span id="busuanzi_value_site_pv"></span>次
  </span>
</div>



  <span class="post-meta-divider">|</span>


-->

<div class="theme-info">
  <i class="fa fa-pencil"></i>
  <span class="post-count">博客全站共361.6k字</span>
</div>


<!-- 
  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>



-->

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
